package com.example.spring.jpa.specification;


import javax.persistence.criteria.*;
import java.lang.reflect.Field;
import java.text.ParseException;
import java.util.Map;

/**
 * @author: orange
 * @create: 2023-07-24 20:14
 * @description:
 */
public class ComplexTypeFacade {
    private final BasicTypeFacade basicTypeFacade;

    public ComplexTypeFacade(BasicTypeFacade basicTypeFacade) {
        this.basicTypeFacade = basicTypeFacade;
    }

    private final PredicateGenerate predicateGenerate = new PredicateGenerate() {
        @Override
        public Predicate generate(GenerateApplicationContext context) throws ParseException {
            Map<String, Object> currMap = context.getObjectMap();
            String[] fieldNames = context.getLeft().split("\\.");
            Path<?> path = null;
            PredicateGenerate predicateGenerate = null;
            for (String fieldName : fieldNames) {
                if (path == null) path = context.getRoot().get(fieldName);
                else path.get(fieldName);

                Object object = currMap.get(fieldName);
                if (object instanceof Map) {
                    currMap = (Map<String, Object>) object;
                } else if (object instanceof Field) {
                    context.setPath(path);
                    predicateGenerate = basicTypeFacade.predicateFormTypeName(((Field) object).getType().getTypeName());
                }
            }
            if (predicateGenerate == null) {
                throw new RuntimeException(String.format("找不到处理的字段%s", context.getLeft()));
            }
            return predicateGenerate.generate(context);
        }
    };

    public PredicateGenerate predicateFormTypeName(String typeName) {
        return predicateGenerate;
    }
}
